<template>
  <el-container>
    <el-aside>
      <div v-if="create11">
        <el-button type="success"   @click="dialogVisibleDir=!dialogVisibleDir">新建</el-button>
      </div>

      <el-input
          v-model="query"
          placeholder="Please enter keyword"
          @input="onQueryChanged"
      />
      <el-tree :data="tableData" :props="props" default-expand-all  @node-click="handleNodeClick" :height="750" id="tree">
        <template #default="{ node, data }">
          <div class="tree_operation" @contextmenu="handleRightClick($event,data,node)">
            <template v-if="data.url">
              <el-icon><Document /></el-icon>
              <span>{{ data.name }}</span>
            </template>
            <template v-else>
              <el-icon><Folder /></el-icon>
              <span >{{ data.name }}</span>
            </template>
          </div>
        </template>
      </el-tree>
    </el-aside>
    <el-main>
      <el-form :model="form" label-width="120px" >
        <el-button @click="CreateRestful" type="warning">创建</el-button>
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="请求地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入url地址"
                        class="input-with-select">
                <template #prepend>
                  <el-select v-model="form.method" class="address_select">
                    <el-option label="GET" value="GET" />
                    <el-option label="HEAD" value="HEAD" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                    <el-option label="DELETE" value="DELETE" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="timeout">
              <el-input v-model="form.timeout" type="number">
                <template #prepend>
                  超时时间
                </template>
              </el-input>
              <el-button @click="Submit" type="success">提交并发送</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs v-model="activeName" type="card" class="head_tabs" style="height: 400px;max-height: 400px">
          <el-tab-pane label="Query" name="query">
            <ApiTable  v-model:data="form.query"></ApiTable>
          </el-tab-pane>
          <el-tab-pane label="Body" name="body">
            <ApiTable  v-model:data="form.body"></ApiTable>

          </el-tab-pane>

          <el-tab-pane label="请求头" name="header">
            <ApiTable  v-model:data="form.header"></ApiTable>
          </el-tab-pane>

          <el-tab-pane label="前置" name="result">
            <el-form-item label="Activity form">
              <el-input v-model="form.desc" type="textarea" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="后置" name="param">(参数)</el-tab-pane>
          <el-tab-pane label="Mock" name="mock">(参数)</el-tab-pane>
        </el-tabs>
      </el-form>

      <div>
        <el-tabs v-model="resp_active" type="card" class="head_tabs" @tab-click="handleClick" style="height: 35vh;max-height:35vh">
          <el-tab-pane label="实时响应" name="resp">
            <json-editor-vue class="editor" v-model="response"  />

          </el-tab-pane>
          <el-tab-pane label="请求头">
          </el-tab-pane>
          <el-tab-pane label="响应头" >
          </el-tab-pane>
          <el-tab-pane label="断言结果" >
          </el-tab-pane>
          <el-tab-pane label="提取结果">

          </el-tab-pane>

        </el-tabs>
      </div>
    </el-main>
  </el-container>
  <div id="custom-menu">
    <ul>
      <li @click="CreateTree">新建目录</li>
      <li  @click="CreateApi">新建工具</li>
      <li>删除</li>
    </ul>
  </div>
  <el-dialog v-model="dialogVisibleDir" title="新建目录" width="25%">
    <el-form :model="form1" label-width="65px">
      <el-form-item label="目录名">
        <el-input v-model="form1.name" :width="120"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleDir = false">取消</el-button>
        <el-button type="primary" @click="OnSubmit">创建</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisible" title="新建子目录" width="25%">
    <el-form :model="form1" label-width="65px">
      <h3>当前目录：{{cur_father}}</h3>
      <el-divider border-style="dashed" />
      <el-form-item label="目录名">
        <el-input v-model="form1.name" :width="120"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="OnSubmit">创建</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref ,onMounted} from 'vue'
import JsonEditorVue from 'json-editor-vue3';
import ApiTable from '@/components/common/tables/api_table.vue'
import { ElTreeV2} from 'element-plus'
import {rest_meau,rest} from './restful'
import {table} from "@/api/table";
import type Node from 'element-plus/es/components/tree/src/model/node'
const tableData = ref([])

const create11 = ref(false)

const form = ref({
  "name": "",
  "method":"GET",
  "url": "http://localhost:8000/api/v1/task",
  "timeout": "",
  "body":[{"k":"","v":""}],
  "query":[{"k":"size","v":"15"},{"k":"page","v":"1"}],
  "assert":[{"k":"","v":""}],
  "header":[{"k":"Content-Type","v":"application/json"},
      {"k":"Token","v":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBfa2V5IjoiMjEyMzJmMjk3YTU3YTVhNzQzODk0YTBlNGE4MDFmYzMiLCJhcHBfc2VjcmV0IjoiYjg2YTJiZTFjZTcwMGM5Yzg3ODAwZTgxNjg4ZTZlMDciLCJleHAiOjE3MDQ1NTc5MzYsImlzcyI6ImFkbWluIn0.RexgaBwsB_EZ0gZDqyIjEcX3Wbxbxm2N6mw-uK7k6vo"}],
})

const response = ref("")

const activeName = ref('header')
const resp_active = ref('resp')


const Submit = async () => {
  response.value = await rest.Run(form.value)
}

interface Tree {
  id:number,
  name: string
  childNodes?: Tree[]
  leaf?: boolean
}

const cur_father = ref("")
const cur_data = ref()
const cur_node = ref(Node)
const form1 = ref({
  name: "",
  father:0,
})

const dialogVisible = ref(false)
const dialogVisibleDir = ref(false)
const dialogVisibleApi = ref(false)
const query = ref('')
const treeRef = ref<InstanceType<typeof ElTreeV2>>()

function handleRightClick(event,data,node) {
  var customMenu = document.getElementById("custom-menu");
  customMenu.style.display = "block";
  customMenu.style.left = event.clientX + 'px';
  customMenu.style.top = event.clientY + 'px';
  cur_data.value = data
  cur_node.value= node
  console.log(node)
}

const props = {
  value: 'name',
  label: 'name',
  children: 'childNodes',
}

const handleNodeClick = async (data) => {
  if (data.url) {
    form.value = data
    return
  }
  var res =  await ListToolChild2(data)
  data.childNodes = res
}

const loadNode = (node, resolve) => {
  if (node.level === 0) {
    return resolve([])
  }
  setTimeout(async () => {
    var data =  await ListToolChild(node)
    data.childNodes = []
    if (data.length == 0) {
      resolve([])
    }else{
      resolve(data)
      for (var i in data) {
        var childs = data[i].childNodes
        console.log(childs)
        for (var j in childs){
          var newChild = {id:childs[j].id,childNodes:[],name:childs[j].name}
          data.childNodes.push(newChild)
        }
      }

    }

  }, 500)
}

onMounted(()=>{
  var tree = document.getElementById("tree");
  tree.addEventListener('contextmenu', function(event) {
    event.preventDefault(); // 取消默认的右键菜单行为
  })

  document.addEventListener('mouseup', function(event) {
    if (event.button === 1 ||event.button == 0) { // event.button表示按下的鼠标按钮编号，2表示右键
      var customMenu = document.getElementById("custom-menu");
      customMenu.style.display = "none";
    }
  });
  ListToolMeau()
})

const onQueryChanged = (query: string) => {
  treeRef.value!.filter(query)
}


const CreateTree = () => {
  cur_father.value = cur_data.value.name
  form1.value.father = cur_data.value.id
  dialogVisible.value = true
  console.log(cur_node.value)
  console.log(cur_data.value)
}

const CreateApi = () => {
  cur_father.value = cur_data.value.name
  form.value.father = cur_data.value.id
  activeName.value = "body"
  dialogVisibleApi.value = true
}

const OnSubmit = async () => {
  if (cur_data.value) {
    if (!cur_data.value.childNodes) {
      cur_data.value.childNodes = []
    }
  }
  var res = await rest_meau.Create(form1.value)
  var newChild = {id:res.data.id,childNodes:[],name:res.data.name}
  cur_data.value.childNodes.push(newChild)
  dialogVisible.value = false
  dialogVisibleDir.value = false
}

const ListToolMeau = async ()=>{
  tableData.value = await rest_meau.List(table.page.value, table.size.value)
}

const ListToolChild = async (node)=>{
  return  await rest_meau.List(table.page.value, table.size.value,{"father":node.data.id})
}

const ListToolChild2 = async (data)=>{
  return  await rest_meau.List(table.page.value, table.size.value,{"father":data.id})
}

const CreateRestful = async () => {
  return await rest.Create(form.value)
}

const SelectApi = ()=>{
  console.log("asd")
}

</script>

<style scoped>
.el-aside {
  width: 200px;
  border-right: 1px solid #a9a4a4;
}

.el-input {
  width: 200px;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  font-family: "方正粗黑宋简体";
  padding-right:8px;
  width: 70px !important;
}
:deep(.el-tabs__header ) {
  margin: 0;
}
.input-with-select {
  width: 95%;
}

.head_tabs {
  height: 500px;
  border: 1px solid #e3dddd;
}

:deep(.el-form-item__content) {
  margin: 0 !important;
}

 :deep(.el-input-group__prepend) {
  padding: 0 8px;
}

:deep(.el-input__wrapper) {
  padding: 1px 8px;
}

:deep(.el-input-group__prepend){
  background-color: rgba(50, 54, 52, 0.7) !important;
  color: white;
}

.address_select {
  color: white;
  outline: unset;
  width: 90px;
  background-color: rgba(164, 162, 163, 0.7) !important;
  margin: 0;
}

:deep(.el-select__icon){
  color: white !important;
}

.address_select :deep(.el-input__inner) {
  color:white !important;
}

.input-with-select  :deep(.el-input-group__prepend) {
  padding: 0;
  width: 80px;
}

.editor {
  height:600px
}

#custom-menu {
  display: none; /* 初始状态下不显示 */
  position: absolute;
  background-color: #f9f9f9;
  font-family: 微软雅黑;
  min-width: 120px;
  border-radius: 10px;
  box-shadow: 3px 3px 4px rgba(0, 0, 0, .2);
}

#custom-menu ul li {
  padding: 8px 16px;
  cursor: pointer;
  list-style: none;
}

#custom-menu ul li:hover {
  background-color: rgba(194, 191, 191, 0.92);
}
</style>